﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace DARE
{
    public class CSplineGroup
    {
        #region fields

        private List<CSpline> m_splines;

        #endregion

        #region properties

        public List<CSpline> Splines { get { return m_splines; } set { m_splines = value; } }

        #endregion

        #region ctor

        public CSplineGroup()
        {
            m_splines = new List<CSpline>();
        }

        #endregion

        #region methods

        public Vector3 GetPosition(float startTime, float endTime, float currentTime, int dir)
        {
            float totalDist = 0;
            float totalTime = endTime - startTime;
            foreach (CSpline spline in m_splines)
                totalDist += spline.Length;
            currentTime = currentTime - startTime;
            float pos = currentTime / totalTime;
            float dist = 0;
            float tmp = 0;
            int i;
            if (dir > 0)
                i = 0;
            else
                i = m_splines.Count - 1;
            for (; i < m_splines.Count && i >= 0; i += dir)
            {
                tmp = m_splines[i].Length;
                if ((dist + tmp) / totalDist > pos)
                    break;
                dist += tmp;
            }
            float t = ((totalDist * pos) - dist) / m_splines[i].Length;
            if (dir <= 0)
                t = 1 - t;
            Vector3 ret = Vector3.Zero;
            if (m_splines[i].ParameterPoints.Length >= 4)
                ret = CSpline.makeBezier(t, m_splines[i].ParameterPoints[0], m_splines[i].ParameterPoints[1], m_splines[i].ParameterPoints[2], m_splines[i].ParameterPoints[3]);
            else if (m_splines[i].ParameterPoints.Length == 3)
                ret = CSpline.makeBezier(t, m_splines[i].ParameterPoints[0], m_splines[i].ParameterPoints[1], m_splines[i].ParameterPoints[2]);
            else if (m_splines[i].ParameterPoints.Length == 2)
                ret = CSpline.makeBezier(t, m_splines[i].ParameterPoints[0], m_splines[i].ParameterPoints[1]);
            else if (m_splines[i].ParameterPoints.Length > 0)
                ret = m_splines[i].ParameterPoints[0];
            return ret;
        }

        #endregion
    }
}
